//
//  LLNewsImageDetialVC.m
//  LoveLove
//
//  Created by 吴志强 on 2019/6/1.
//  Copyright © 2019 wkf. All rights reserved.
//

#import "LLNewsImageDetialVC.h"
#import "DetailNewsView.h"
#import "DetailsToolBar.h"
#import "QZTopTextView.h"
#import "LLLoginViewController.h"
#import "imageCell.h"
#import "PicsView.h"
#import "CommentCell.h"
#import "CommentModel.h"
#import "CommentFrame.h"
#import "replay_detial_VC.h"

#import "UIImageView+WebCache.h"//图片加载
#import "ImageBrowserViewController.h"

#import "PhotoView.h"

@interface LLNewsImageDetialVC ()<QZTopTextViewDelegate,UITableViewDelegate,UITableViewDataSource,PhotoViewDelegate>

@property (nonatomic,strong) DetailNewsView *detailNewsView;

@property (nonatomic,strong) DetailsToolBar *detailsToolBar;

@property (nonatomic,strong) UITableView *tableView;

/**
 评论框
 */
@property (nonatomic,strong) QZTopTextView *commentTextView;

@property (nonatomic,strong) NSDictionary *newsDict;

@property (nonatomic,strong) NSArray *array;

@property (nonatomic,strong) NSMutableArray *dataArray;


@property (nonatomic,assign) BOOL isReturn;//是否回复

@property (nonatomic,strong) NSDictionary *returnDic;

@property (nonatomic,copy) NSArray *comment_array;
@end

@implementation LLNewsImageDetialVC
-(QZTopTextView *)commentTextView{
    if (!_commentTextView) {
        _commentTextView = [QZTopTextView new];
        _commentTextView.isNavi = YES;
        _commentTextView.delegate = self;
    }
    return _commentTextView;
}
-(NSDictionary *)newsDict{
    if (!_newsDict) {
        _newsDict = [NSDictionary dictionary];
    }
    return _newsDict;
}
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.redColor;
    self.navigationItem.title = self.model.u_name;
        // Do any additional setup after loading the view.

    self.titleView.backgroundColor = LLColor(227, 15, 29);

    [self initWindow];
    [self getNewsCommentRequst];
    [self getNewsDetailRequst];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self getNewsCommentRequst];
    }];
        //    [self.detailNewsView mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.left.equalTo(self.view.mas_left);
        //         make.right.equalTo(self.view.mas_right);
        //         make.top.equalTo(self.view.mas_top);
        ////         make.bottom.equalTo(self.view.mas_bottom).with.offset(-40);
        //    }];

    self.detailsToolBar = [[DetailsToolBar alloc]init];
    [self.view addSubview:self.detailsToolBar];
    [self.detailsToolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.tableView.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    WeakSelf(weakSelf);
    LLUserInfo *user = [LLUserInfo sharedUser];
    self.detailsToolBar.toolBarBlock = ^(NSInteger type,BOOL isSelected) {
        NSLog(@"%ld",type);
        if(!user.isLogin){
            LLLoginViewController *vc =  LLLoginViewController.new;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            return ;
        }
        if (type == 0) {
            if (!user.isLogin) {
                LLLoginViewController *vc = [LLLoginViewController new];
                [weakSelf.navigationController pushViewController:vc animated:YES];

            }else{
                weakSelf.isReturn = NO;
                [weakSelf.commentTextView.countNumTextView becomeFirstResponder];
            }

        }else if(type == 1){
            [weakSelf dianZan:isSelected];
        }else{

        }
    };
    [self.view addSubview:self.commentTextView];//评论框
}

-(void)initWindow{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        //    _tableView.backgroundColor = [UIColor redColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.backgroundColor = UIColor.whiteColor;
    _tableView.estimatedSectionHeaderHeight = 70;
        //    _tableView.estimatedSectionFooterHeight = 0;
        //    _tableView.estimatedRowHeight = 0;
        //    _tableView.rowHeight = UITableViewAutomaticDimension; //

    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            if (iPhoneX) {
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).with.offset(-44);
            }else{
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).with.offset(-20);
            }
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).with.offset(-40);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        } else {
            make.edges.mas_offset(UIEdgeInsetsMake(0, 0, 40, 0));
        }
    }];

        //    _tableView.tableHeaderView = self.headView;
        //    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        //
        //    }];
}
#pragma mark----tableviewdelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return section == 0 ? self.array.count :self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *string = @"imageCell";
        imageCell *cell = [[imageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
        cell.img_url = self.array[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    CommentCell *cell = [CommentCell commentCellWithTableView:tableView andIndexPath:indexPath];
    CommentFrame *frame = self.dataArray[indexPath.row];
    cell.commentFrame = frame;
    cell.zanBtn.tag = 100 +indexPath.row;
    [cell.zanBtn addTarget:self action:@selector(pushDetail:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
    
}
-(void)pushDetail:(UIButton *)button{
    NSInteger index = button.tag - 100;
    NSLog(@"%ld",index);
    CommentFrame *frame = self.dataArray[index];
    NSArray *commentArr =  frame.commentModel.comm;

    if (commentArr.count > 0) {

        replay_detial_VC *vc = [replay_detial_VC new];
        vc.data_array = frame.commentModel.comm;
        vc.newsId = self.model.newsId;
        vc.commentId = frame.commentModel.commentId;
        WeakSelf(weakSelf);
        vc.commentBlock = ^{
            weakSelf.page = 1;
            [weakSelf.dataArray removeAllObjects];
            [weakSelf getNewsCommentRequst];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

//    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.array[indexPath.row]]]];
    if(indexPath.section == 0){
        return 200;
    }else{
        return [self.dataArray[indexPath.row]  rowHeight];
        
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

        __weak typeof(self) weakSelf=self;

        [ImageBrowserViewController show:self type:PhotoBroswerVCTypeModal index:indexPath.row imagesBlock:^NSArray *{
            return weakSelf.array;
        } tapDownload:^(NSString *string) {

            [weakSelf toSaveImage:string];
        }];
//        PicsView *picView = [[PicsView alloc] initWithImages:self.array AtIndex:indexPath.row];
//        picView.removeView = ^(){
//
//        };
//        [picView showView];
    }
    else {
//
        LLUserInfo *user = [LLUserInfo sharedUser];
        if(!user.isLogin){
            LLLoginViewController *vc =  LLLoginViewController.new;
            [self.navigationController pushViewController:vc animated:YES];
            return ;
        }
        CommentFrame *frame = self.dataArray[indexPath.row];
        CommentModel *commentModel = frame.commentModel;
        self.isReturn = YES;
        self.returnDic = @{@"c_id":commentModel.commentId,@"uid":commentModel.postUid};
        [self.commentTextView.countNumTextView becomeFirstResponder];
    }
}

#pragma mark---QZTopTextViewDelegate
- (void)sendComment:(NSString *)comment{

    NSString *commentStr = self.commentTextView.countNumTextView.text;
    if (commentStr.length == 0) {
        [self showSVProgressHUDInfoWithsStatus:@"请输入内容"];
        return;
    }
    [self commitComment:commentStr];
}

#pragma mark---新闻详情页
-(void)getNewsDetailRequst{
    LLUserInfo *user = [LLUserInfo sharedUser];

    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary: @{@"edu_id":@"14",@"new_id":self.model.newsId}];

    if (user.isLogin) {
        [dic setObject:user.user_id forKey:@"user_id"];
        [dic setObject:user.user_random forKey:@"user_random"];
    }
    [self showSVProgressHUD];
    [LLHttpTool post:LLHOST
          headParams:nil
              params:dic
             success:^(NSDictionary *result) {

                 [SVProgressHUD dismiss];
                 self.newsDict = result[@"data"];

                 CGFloat contentTextH = [CommonTools sizeOfText:self.newsDict[@"article"] fontSize:15 width:LLScreenWidth-2*18].height;
                 CGFloat titleH = [CommonTools sizeOfText:self.newsDict[@"new_title"] fontSize:23 width:LLScreenWidth-2*18].height;
                 self.detailNewsView = [[DetailNewsView alloc]initWithFrame:CGRectMake(0, 0, LLScreenWidth, contentTextH+titleH+230)];
                 self.tableView.tableHeaderView = self.detailNewsView;
                     //    [self.tableView addSubview:self.detailNewsView];
                     //    [self.view addSubview:self.detailNewsView];
                 [self.detailNewsView.detailSubview.likeBtn addTarget:self action:@selector(guanZhu:) forControlEvents:UIControlEventTouchUpInside];

                 self.array = self.newsDict[@"img_url"];

                 [self.detailNewsView configDetailNewsView:self.newsDict];

                 self.comment_array = @[@"0",[NSString stringWithFormat:@"%@",self.newsDict[@"like_num"]],@"0"];
                 [self.detailsToolBar update:self.comment_array];
                 [self.tableView reloadData];

             } failure:^(NSString *msg) {

                 [SVProgressHUD showErrorWithStatus:msg];
             }];
}
#pragma mark---获取评论
-(void)getNewsCommentRequst{
    LLUserInfo *user = [LLUserInfo sharedUser];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary: @{@"edu_id":@"23",@"new_id":self.model.newsId,@"page":@(self.page)}];

    [self showSVProgressHUD];
    [LLHttpTool post:LLHOST
          headParams:nil
              params:dic
             success:^(NSDictionary *result) {
                 [self.tableView.mj_footer endRefreshing];
                 [SVProgressHUD dismiss];
                 NSDictionary *dict = result[@"data"];
                 NSArray *resultArray = [CommentModel commentModelsList:dict];
                 if (resultArray.count == 0 && self.page != 1) {
                     [self.tableView.mj_footer endRefreshingWithNoMoreData];
                 }
                 for (CommentModel *model in resultArray) {
                     CommentFrame *frame = [CommentFrame new];
                     frame.commentModel = model;
                     [self.dataArray addObject:frame];
                 }
                 self.page++;
                 [self.tableView reloadData];
                 
             } failure:^(NSString *msg) {
                 
                 [SVProgressHUD showErrorWithStatus:msg];
             }];
}


//点赞
-(void)dianZan:(BOOL)isSelected{
        //edu_id:18(固定值)
        //new_id: 新闻id
        //    user_id; 用户id
        //user_random: 随机数    is_love: 1是点赞，0是取消点赞
    NSInteger islove;
    if(isSelected){
        islove = 1;
    }else{
        islove = 0;
    }

    LLUserInfo *user = [LLUserInfo sharedUser];
    if (!user.isLogin) {
        LLLoginViewController *vc = [LLLoginViewController new];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }

    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary: @{@"edu_id":@"17"}];
    [dic setObject:user.user_id forKey:@"user_id"];
    [dic setObject:user.user_random forKey:@"user_random"];
    [dic setObject:@(islove) forKey:@"is_love"];
    [dic setObject:self.model.newsId forKey:@"new_id"];
    [self showSVProgressHUD];
    [LLHttpTool post:LLHOST headParams:nil params:dic success:^(NSDictionary *result) {

        int count = [self.newsDict[@"like_num"] intValue];

        if (isSelected) {

            count++;

            [self showSVProgressHUDInfoWithsStatus:@"点赞成功"];
            self.page = 1;
            [self.dataArray removeAllObjects];
            [self getNewsCommentRequst];
        }else{


            [self showSVProgressHUDInfoWithsStatus:@"取消点赞"];
        }

        self.comment_array = @[@"0",[NSString stringWithFormat:@"%d",count],@"0"];
        [self.detailsToolBar update:self.comment_array];

    } failure:^(NSString *msg) {
        [SVProgressHUD showErrorWithStatus:msg];
    }];
}


/**
 发表评论

 @param comment 内容
 */
-(void)commitComment:(NSString *)comment{

    LLUserInfo *user = [LLUserInfo sharedUser];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"22" forKey:@"edu_id"];
    [dic setObject:user.user_id forKey:@"user_id"];
    [dic setObject:user.user_random forKey:@"user_random"];
    [dic setObject:comment forKey:@"comment"];
    [dic setObject:self.model.newsId forKey:@"new_id"];
    if (self.isReturn) {
          [dic setObject:self.returnDic[@"c_id"] forKey:@"c_id"];
         [dic setObject:self.returnDic[@"uid"] forKey:@"uid"];
    }
    
    [self showSVProgressHUD];

    [LLHttpTool post:LLHOST headParams:nil params:dic success:^(NSDictionary *result) {
            //        [SVProgressHUD dismiss];
        if([result[@"code"] integerValue] == 0){
            [self showSVProgressHUDInfoWithsStatus:@"发表成功"];
        }else
        [self showSVProgressHUDInfoWithsStatus:result[@"msg"]];

    } failure:^(NSString *msg) {
        [SVProgressHUD showErrorWithStatus:msg];
    }];
}


-(void)guanZhu:(UIButton *)button{
    
    if (![LLUserInfo sharedUser].isLogin) {
        LLLoginViewController *vc = [LLLoginViewController new];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }

    button.selected = !button.selected;
        //edu_id:15(固定值)
        //user_id:  用户id
        //new_uid:  新闻发布者的id     user_random: 随机数
        //is_follow: 1是关注，0是取消关注
    NSInteger islove;
    if(button.selected){
        islove = 1;
    }else{
        islove = 0;
    }
    LLUserInfo *user = [LLUserInfo sharedUser];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary: @{@"edu_id":@"15"}];
    [dic setObject:user.user_id forKey:@"user_id"];
    [dic setObject:user.user_random forKey:@"user_random"];
    [dic setObject:self.newsDict[@"new_uid"] forKey:@"new_uid"];
    [dic setObject:@(islove) forKey:@"is_follow"];
    [self showSVProgressHUD];
    [LLHttpTool post:LLHOST headParams:nil params:dic success:^(NSDictionary *result) {
            //        [SVProgressHUD dismiss];
        if (islove == 1) {

            [self showSVProgressHUDInfoWithsStatus:@"关注成功"];
        }else{

            [self showSVProgressHUDInfoWithsStatus:@"取消关注"];
        }

    } failure:^(NSString *msg) {
        [SVProgressHUD showErrorWithStatus:msg];
    }];
}

- (void)toSaveImage:(NSString *)urlString {

    [SVProgressHUD show];

    NSURL *url = [NSURL URLWithString: urlString];

    UIImage *img;
        //从网络下载图片
    NSData *data = [NSData dataWithContentsOfURL:url];
    img = [UIImage imageWithData:data];
        // 保存图片到相册中
    UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);

}
    //保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo
{
    [SVProgressHUD dismiss];

    if (error != NULL) {

        [SVProgressHUD showErrorWithStatus:@"图片保存失败!"];
    } else {

        [SVProgressHUD showSuccessWithStatus:@"图片保存成功!"];
    }
}


@end
